<template>
  <div class="spaceManagement">
    <a-flex justify="space-between">
      <h2>空间管理</h2>
      <a-space>
        <a-button
          type="primary"
          :href="`/space/addSpace/${SPACE_TYPE_ENUM.PRIVATE}`"
          target="_blank"
          >创建空间</a-button
        >
        <a-button type="primary" :href="`/space/addSpace/${SPACE_TYPE_ENUM.TEAM}`" target="_blank"
          >创建团队空间</a-button
        >
        <a-button type="primary" href="/analyze/picture?queryAll=1" target="_blank"
          >全图库分析</a-button
        >
        <a-button type="primary" href="/analyze/picture?queryPublic=1" target="_blank"
          >公共图库分析</a-button
        >
      </a-space>
    </a-flex>
    <!-- 搜索框 -->
    <a-form layout="inline" :model="queryParams" @finish="doSearch" style="margin-bottom: 16px">
      <a-form-item label="空间名称">
        <a-input v-model:value="queryParams.spaceName" placeholder="请输入空间名称" />
      </a-form-item>
      <a-form-item label="空间级别">
        <a-select
          v-model:value="queryParams.spaceLevel"
          placeholder="请选择空间级别"
          allowClear
          style="width: 160px"
          :options="SPACE_LEVEL_OPTIONS"
        ></a-select>
      </a-form-item>
      <a-form-item label="空间类别">
        <a-select
          v-model:value="queryParams.spaceType"
          placeholder="请选择空间类别"
          allowClear
          style="width: 160px"
          :options="SPACE_TYPE_OPTIONS"
        ></a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="margin-left: 16px">搜索</a-button>
      </a-form-item>
    </a-form>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doChange"
      :rowKey="(record) => record.id"
    >
      <template #bodyCell="{ column, record }">
        <!--        空间级别特殊处理 -->
        <template v-if="column.dataIndex === 'spaceLevel'">
          <div>{{ SPACE_LEVEL_MAP[record.spaceLevel] }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'spaceType'">
          <div>{{ SPACE_TYPE_MAP[record.spaceType] }}</div>
        </template>
        <!--        使用情况特殊处理-->
        <template v-else-if="column.dataIndex === 'spaceUseInfo'">
          <div>大小：{{ formatSize(record.totalSize) }} / {{ formatSize(record.maxSize) }}</div>
          <div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
        </template>
        <!-- 时间特殊处理-创建时间 -->
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <!-- 时间特殊处理-编辑时间 -->
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              更多操作
              <DownOutlined />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <a-popconfirm
                    title="确认删除?"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="deleteById(record.id)"
                    @cancel="cancel"
                  >
                    <a style="display: block; text-align: center">删除</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item>
                  <a-button type="link" :href="`/space/addSpace?id=${record.id}`" target="_blank"
                    >编辑
                  </a-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { DownOutlined } from '@ant-design/icons-vue'
import { adminSpacePageUsingPost, deleteSpaceByIdUsingPost } from '@/api/spaceController.ts'
import { SPACE_LEVEL_MAP, SPACE_LEVEL_OPTIONS } from '@/constants/space.ts'
import { formatSize } from '@/utils'
import { SPACE_TYPE_ENUM, SPACE_TYPE_MAP, SPACE_TYPE_OPTIONS } from '@/constants/spaceUser.ts'

// 定义表格数据
const dataList = ref<API.Space[]>([])
// 定义总条数
const total = ref(0)
// 定义查询参数,默认1页10条
const queryParams = reactive<API.SpaceQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'editTime',
  sortOrder: 'descend',
})

// 定义分页对象
const pagination = computed(() => {
  return {
    current: queryParams.current,
    pageSize: queryParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

// 从后端分页查询数据
async function getPageData() {
  const resp = await adminSpacePageUsingPost({ ...queryParams })
  if (resp.data.code === 0 && resp.data.data) {
    dataList.value = resp.data.data.records ?? []
    total.value = resp.data.data.total ?? 0
  } else {
    message.error('查询用户空间数据失败,' + resp.data.message)
  }
}

// 表格分页变化
function doChange(record: any) {
  queryParams.current = record.current
  queryParams.pageSize = record.pageSize
  getPageData()
}

// 搜索
function doSearch() {
  queryParams.current = 1
  getPageData()
}

// 删除
async function deleteById(id: string) {
  const resp = await deleteSpaceByIdUsingPost({ id })
  if (resp.data.code === 0) {
    message.success('删除成功')
    getPageData()
  } else {
    message.error('删除失败,' + resp.data.message)
  }
}

const cancel = (e: MouseEvent) => {
  message.error('取消')
}

// 页面加载时获取数据
onMounted(() => {
  getPageData()
})

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '空间名称',
    dataIndex: 'spaceName',
  },
  {
    title: '空间级别',
    dataIndex: 'spaceLevel',
  },
  {
    title: '空间类别',
    dataIndex: 'spaceType',
  },
  {
    title: '使用情况',
    dataIndex: 'spaceUseInfo',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]
</script>

<style scoped>
/* 可以添加一些编辑状态的样式 */
:deep(.ant-table-cell) {
  transition: background-color 0.2s;
}

:deep(.ant-table-cell:hover) {
  background-color: #f5f5f5;
}
</style>
